import React from 'react';
import { connect } from 'dva';
// import styles from './User.css';
import {
  Form, Input, Button, Icon, Table, Menu, Dropdown, Popover, Checkbox, Modal, notification
} from 'antd';
import AdduserForm from './Adduser'

function User({ dispatch, Usersdata, operationUser, loading, 
   current,  form, filter, deletevisible, fileName, validColumns, fileToken,addUser,
     fileType, total, ChangePasswordvisible, powervisible }) {

  const Search = Input.Search;
  const { getFieldDecorator } = form;

  let paginationOnchange = (page) => {

    dispatch({
      type: 'user/setState',
      payload: {    
        loading: false,
        current: page
      }
    })


  }

  let sortOnchange = (a, b, c) => {
    console.log(c)
    
    
    if(c.order == "ascend"){
      dispatch({
        type: 'user/userToAsc',
        payload: {
          key :c.columnKey
        }
      });
    }
    else {
      dispatch({
        type: 'user/userToDesc',
        payload: {
          key :c.columnKey
        }
      });
    }

  }

  function search(e) {

    dispatch({
      type: "user/setState",
      payload: {
        filter: e.target.value
      }
    })
    dispatch({
      type: "user/getuser",
      payload: {
        filter: e.target.value
      }
    })
  }

 
  const fullColumns = [
    {
      title: '用户注册时间',
      dataIndex: 'insertdate',
      key: 'insertdate',
      sorter: true
    }, {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName',
      sorter: true,
    }, {
      title: '是否是会员',
      dataIndex: 'isvip',
      key: 'isvip',
      sorter: true,
      render: (text, record) => <span>{record.isVip.data[0]== 1 ? <span color="blue">会员</span> : '非会员'}</span>
    }, {
      title: '操作',
      key: 'action',
      dataIndex: 'action',
      // fixed: 'right',
      render: (text, record) => {
        const menu = (
          <Menu>
            {/* <Menu.Item>
              <a onClick={() => {
                console.log(record)
              
                dispatch({
                  type: 'user/getEdit',
                  payload: {
                    id: record.id,
                  }
                })
              }}>编辑</a>
            </Menu.Item> */}
            <Menu.Item>
            <a onClick={() => {
                dispatch({
                  type: 'user/setState',
                  payload: {
                    powervisible: true,
                    operationUser:{
                      userId: record.id,
                    }
                  }
                })
              }}>修改权限</a>
            </Menu.Item>
       
            <Menu.Item>
              <a onClick={() => {
                dispatch({
                  type: 'user/setState',
                  payload: {
                    ChangePasswordvisible: true,
                    operationUser:{
                      userId: record.id,
                    }
                  

                  }
                })
              }}>修改密码</a>
            </Menu.Item>

            <Menu.Item >
              <a onClick={() => {
                console.log(record)
                // 删除功能已注释
                dispatch({
                  type: 'user/setState',
                  payload: {
                    deletevisible: true,
                    operationUser:{
                      userId:record.id,
                      userName: record.userName
                    } 
                  }
                })
              }}>删除</a>
            </Menu.Item>
          </Menu>
        )
        return (
          <span>
            <Dropdown overlay={menu}>
              <a className="ant-dropdown-link" onClick={() => console.log(record)}>操作 <Icon type="down" /></a>
            </Dropdown>,
        </span>
        )
      }
    }];

  let columns = fullColumns.filter(
    function (column) {
      return validColumns.filter((v) => (v == column.dataIndex)).length > 0
      // return (column.dataIndex in validColumns)
    }
  )

  function onChange(dataIndex, e) {
    if (e.target.checked) {
      validColumns.push(dataIndex)
    } else {
      validColumns = validColumns.filter((v) => (v != dataIndex));
    }
    dispatch({
      type: "user/setState",
      payload: { validColumns: JSON.parse(JSON.stringify(validColumns)) }
    })
  }
  const content = (
    <div style={{ width: 250 }}>
      {
        fullColumns.map((column) => (<Checkbox
          checked={validColumns.filter((v) => (v == column.dataIndex)).length > 0}
          onChange={onChange.bind(this, column.dataIndex)}
        >{column.title}
        </Checkbox>))
      }
    </div>
  )

  let handleCancel = (e) => {
    dispatch({
      type: 'user/setState',
      payload: {
        deletevisible: false,
        ChangePasswordvisible: false,
        powervisible: false
      }
    })
  }
  function ShowaddUser() {
    dispatch({
      type: 'user/setState',
      payload: {
        addUser:{
          addUservisible:true
        }
      }
    })
  }

  function UsertoVip(){
    dispatch({
      type: 'user/changeUserPower',
      payload: {        
        operationUser:{
          vip:1
        }
      }
    })
    
  }
  function UsertoNoVip(){
    dispatch({
      type: 'user/changeUserPower',
      payload: {        
        operationUser:{
          vip:0
        }
      }
    })
  }
  function onShowSizeChange(current, pageSize) {
    // dispatch({
    //   type: 'user/fetch',
    //   payload: {
    //     current: current,
    //     filter: filter,
    //     maxResultCount: pageSize,
    //     name: "",
    //     pageSize: pageSize,
    //     phoneNumber: "",
    //     showQuickJumper: true,
    //     showSizeChanger: true,
    //     size: "large",
   
       
    //     total: 22,
    //     userName: ""
    //   }
    // })
  }

  const deleteUser = () => {
    dispatch({
      type: 'user/delete',
      payload: {
        id: operationUser.userId,
      }
    })

  };
  const ChangeUserPassword = (e) => {
    console.log(1)
    e.preventDefault();
    form.validateFields((errors, values) => {
      if (!!errors) {
        console.log('Errors in form!!!');
        return;
      }
      console.log(values.password)
      dispatch({
        type: 'user/ChangeUserPassword',
        payload: {//可以不填
           userId:operationUser.id,
          newPassword: values.password

        },
      })
    });
  }

  let compareToFirstPassword = (rule, value, callback) => {

    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码不同!');
    } else {
      callback();
    }
  }
  let inspectPassword = (rule, value, callback) => {
    var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/;
    if (value && !reg.test(value)) {
      callback('密码长度要大于6位，由数字和字母组成');
    } else {
      callback();
    }
  }

  // let editUser = () => {
  //   dispatch({
  //     type: 'user/editUser',
  //     payload: {
  //     }
  //   })
  // }


  
 
  return (

    <div >
      <Search
        placeholder="请输入搜索字段"
        onPressEnter={search}
        style={{ width: 400, marginBottom: 10 }}
      />
      <br />
      <Button type="primary" onClick={ShowaddUser} >
        添加用户
     </Button>
      
    <AdduserForm/>

      <Popover placement="bottom" content={content} title="Title" >
        <Button style={{ float: 'right' }}>
          自定义列表条目 <Icon type="down" />
        </Button>
      </Popover>

      <Table rowKey="id" loading={loading}  bordered columns={columns} dataSource={Usersdata} size="middle" scroll={{ x: 1500 }}
        pagination={{ showQuickJumper: true, showSizeChanger: true, 
          onShowSizeChange: onShowSizeChange, total: Usersdata.length,
           current: current, onChange: paginationOnchange }}
        onChange={sortOnchange} style={{ marginTop: 20 }}
      />

      <Modal
        title="删除用户"
        visible={deletevisible}
        onOk={deleteUser}
        onCancel={handleCancel}

      >
        您想删除该用户？
      </Modal>
      
      <Modal
        title="修改用户权限"
        visible={powervisible}
        onOk={UsertoVip}
        onCancel={UsertoNoVip}
        okText="会员用户"
        cancelText="非会员用户"
      >
        您想将用户修改为？
      </Modal>
          
          {
            ChangePasswordvisible?   <Modal
            title="修改用户密码"
            visible={ChangePasswordvisible}
            onOk={ChangeUserPassword}
            onCancel={handleCancel}
          >
            <Form onSubmit={ChangeUserPassword} >
            
              <Form.Item
                label="密码" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}
              >
                {getFieldDecorator('password', {
                  rules: [{
                    required: true, message: '请输入密码!',
                  }, {
                    validator: inspectPassword,
                  }],
                })(
                  <Input type="password" />
                )}
              </Form.Item>
              <Form.Item
                label="确认密码" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}
              >
                {getFieldDecorator('confirm', {
                  rules: [{
                    required: true, message: '请再次输入密码!',
                  }, {
                    validator: compareToFirstPassword,
                  }],
                })(
                  <Input type="password" />
                )}
              </Form.Item>
            </Form>
          </Modal>:null
          }
    
      {/* <Modal
        title="编辑用户"
        visible={editVisible}
        onOk={editUser}
        onCancel={handleCancel}

      >
      
      </Modal> */}
    </div>
  );
}
const Changepassword = Form.create({ name: 'changepasswordForm' })(User);
export default connect(({ user }) => ({ ...user }))(Changepassword);